import { FC, useEffect, useState, useRef } from "react";
import { css } from "@emotion/css";
import { Popover, Progress } from "@arco-design/web-react";
import * as echarts from "echarts";
import "echarts-liquidfill";
// import { useAPI } from "../../hooks/useAPI.ts";
import "./SleepReport.css";
import overview from "../../assets/images/dashboard/overview-icon.png";
import bed from "../../assets/images/dashboard/Bed-icon.png";
import sleepIcon from "../../assets/images/dashboard/sleep-icon.png";
import awake from "../../assets/images/dashboard/awake-icon.png";
import sleep from "../../assets/images/dashboard/sleep.png";
import average from "../../assets/images/dashboard/average.png";

const reversedArray = [18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8];
function diffTimeList(data: any) {
  data = data.map((item: any) => {
    item.time = diffTime(item.time);
    item.time = processTimeBlocks(item.time);
    return item;
  });

  return data;
}
function diffTime(time: any) {
  time = time.map((item: any) => {
    // 解析 startTime 和 endTime
    const start: any = new Date(item.startTime);
    const end: any = new Date(item.endTime);

    // 计算 startTime 距离今天 0 点的时间差（分钟）
    const startOfDay: any = new Date(
      start.getFullYear(),
      start.getMonth(),
      start.getDate()
    ); // 当天 0 点
    let startMinutesFromZero = Math.floor((start - startOfDay) / (1000 * 60)); // 转换为分钟 再转成距离
    let left = startMinutesFromZero;

    // 计算时间区间的差值（分钟）
    const durationMilliseconds = end - start;
    const durationMinutes = Math.floor(durationMilliseconds / (1000 * 60)); // 转换为分钟 再转成距离
    let width = durationMinutes;
    width = width > 6 ? width : 6;
    const formatTime = (date: any) => {
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      return `${hours}:${minutes}`;
    };
    const timeRange = `${formatTime(start)}-${formatTime(end)}`;
    const formatDuration = (minutes: any) => {
      if (minutes >= 60) {
        const hours = Math.floor(minutes / 60);
        const remainingMinutes = minutes % 60;
        return remainingMinutes === 0
          ? `${hours}小时`
          : `${hours}小时${remainingMinutes}分钟`;
      } else {
        return `${minutes}分钟`;
      }
    };
    const formattedDuration = formatDuration(durationMinutes);

    // 格式化时间区间为 'HH:mm-HH:mm'
    // 提取 startTime 和 endTime 为字符串属性
    const startTimeStr = formatTime(start);
    const endTimeStr = formatTime(end);
    // 返回新的对象
    return {
      ...item,
      startMinutesFromZero,
      durationMinutes,
      left,
      width,
      timeRange,
      formattedDuration,
      startTimeStr,
      endTimeStr,
    };
  });
  return time;
}
function processTimeBlocks(arr: any) {
  // 将时间字符串转换为分钟数
  const timeToMinutes = (timeStr: any) => {
    const [hours, minutes] = timeStr.split(":").map(Number);
    return hours * 60 + minutes;
  };

  // 比较两个时间区间的大小（用于排序）
  const compareTimeRanges = (a: any, b: any) => {
    const aStart = a.split("-")[0];
    const bStart = b.split("-")[0];
    return aStart.localeCompare(bStart);
  };

  return arr.map((current: any) => {
    // 初始化结果（包含自身）
    const result = {
      ...current,
      title: [`${current.startTimeStr}-${current.endTimeStr}`],
      num: current.minutes,
    };

    // 如果width > 6，直接返回自身
    if (current.width > 6) {
      // 对title排序（虽然只有自身一个元素）
      result.title.sort(compareTimeRanges);
      return result;
    }

    // width <= 6 时，检查其他项
    const currentStart = timeToMinutes(current.startTimeStr);
    const currentEnd = timeToMinutes(current.endTimeStr);

    arr.forEach((other: any) => {
      // 跳过自身比较
      if (current === other) return;

      const otherStart = timeToMinutes(other.startTimeStr);
      const otherEnd = timeToMinutes(other.endTimeStr);

      // 计算时间差（取绝对值）
      const timeDiff = Math.min(
        Math.abs(currentStart - otherStart),
        Math.abs(currentStart - otherEnd),
        Math.abs(currentEnd - otherStart),
        Math.abs(currentEnd - otherEnd)
      );

      // 如果时间差小于10分钟，则视为相关
      if (timeDiff < 10) {
        result.title.push(`${other.startTimeStr}-${other.endTimeStr}`);
        result.num += other.minutes;
      }
    });

    // 对title数组按开始时间排序
    result.title.sort(compareTimeRanges);

    return result;
  });
}

function timeToMinutes(timeStr: string) {
  // 将时间字符串拆分为小时、分钟、秒
  const [hours, minutes, seconds] = timeStr.split(":").map(Number);
  // 计算总分钟数（小时转分钟 + 分钟 + 秒转分钟）
  const totalMinutes = hours * 60 + minutes + Math.floor(seconds / 60);

  return totalMinutes;
}
function timeToMinuteStr(timeStr: string) {
  // 将时间字符串拆分为小时、分钟、秒
  const [hours, minutes] = timeStr.split(":").map(Number);
  let hourStr = hours > 0 ? `${hours}小时` : ``;
  let minuteStr = minutes > 0 ? `${minutes}分钟` : ``;
  // 计算总分钟数（小时转分钟 + 分钟 + 秒转分钟）
  const totalMinutes = `${hourStr}${minuteStr}`;
  return totalMinutes;
}

const initData = [
  {
    rightBackground: "#F3F4FF",
    borderColor: "#FFCBC3",
    leftBackground: "#798AFF",
    name: "清醒时间",
    timeStr: "2小时10分钟",
    time: [
      {
        startTime: "2025-04-16 00:00:00",
        endTime: "2025-04-16 01:00:00",
      },
      {
        startTime: "2025-04-16 03:30:00",
        endTime: "2025-04-16 04:40:00",
      },
    ],
  },
  {
    name: "快速动眼睡眠",
    timeStr: "3小时36分钟",
    rightBackground: "#FFF4E4",
    borderColor: "#FFCBC3",
    leftBackground: "#FF9900",
    time: [
      {
        startTime: "2025-04-16 01:00:00",
        endTime: "2025-04-16 01:30:00",
      },
      {
        startTime: "2025-04-16 04:40:00",
        endTime: "2025-04-16 07:40:00",
      },
      {
        startTime: "2025-04-16 09:10:00",
        endTime: "2025-04-16 10:10:00",
      },
      {
        startTime: "2025-04-16 11:10:00",
        endTime: "2025-04-16 12:00:00",
      },
    ],
  },
  {
    name: "核心睡眠",
    timeStr: "2小时36分钟",
    rightBackground: "#FFEFEF",
    borderColor: "#FFCBC3",
    leftBackground: "#FF6969",
    time: [
      {
        startTime: "2025-04-16 01:30:00",
        endTime: "2025-04-16 02:30:00",
      },
      {
        startTime: "2025-04-16 07:40:00",
        endTime: "2025-04-16 09:10:00",
      },
    ],
  },
  {
    name: "深度睡眠",
    timeStr: "3小时36分钟",
    rightBackground: "#F4F0FF",
    borderColor: "#FFCBC3",
    leftBackground: "#8358F6",
    time: [
      {
        startTime: "2025-04-16 02:30:00",
        endTime: "2025-04-16 03:30:00",
      },
      {
        startTime: "2025-04-16 10:10:00",
        endTime: "2025-04-16 11:10:00",
      },
    ],
  },
];
const initHistoryEcahrtsData = [
  { date: "21号", value: "11:00:00" },
  { date: "22号", value: "10:30:00" },
  { date: "23号", value: "10:00:00" },
  { date: "24号", value: "09:30:00" },
  { date: "25号", value: "07:00:00" },
  { date: "26号", value: "08:20:00" },
  { date: "27号", value: "07:50:00" },
];

export const SleepReport: FC<{ roomId: number | string }> = ({ roomId }) => {
  console.log("roomId==", roomId);
  const [data, setData] = useState([]);
  const [historyEcahrtsData, setHistoryEcahrtsData] = useState<any>([]);
  const [averageNum, setAverageNum] = useState(0);

  // const api = useAPI();
  const historyRef = useRef<HTMLDivElement>(null);
  const sleepQualityRef = useRef(null);
  const sleepEfficiencyRef = useRef(null);

  useEffect(() => {
    setData([]);
    setData(diffTimeList(initData));
  }, []);
  useEffect(() => {
    const formatterhistoryEcahrtsData = () => {
      if (historyRef.current) {
        let width = historyRef.current.offsetWidth / 7;
        let historyEcahrtsArr = initHistoryEcahrtsData.map((item, index) => {
          return {
            ...item,
            left: width * index + width / 2 - 10,
            height: timeToMinutes(item.value) / 4,
            title: timeToMinuteStr(item.value),
          };
        });
        const averagevalue = historyEcahrtsArr.reduce(
          (accumulator, currentValue) => accumulator + currentValue.height,
          0
        );

        setHistoryEcahrtsData(historyEcahrtsArr);
        setAverageNum(averagevalue / 7);
        console.log(averagevalue / 7);
      }
    };

    formatterhistoryEcahrtsData();
  }, [historyRef.current !== null]);

  useEffect(() => {
    if (sleepQualityRef.current) {
      const chartInstance = echarts.init(sleepQualityRef.current);
      const option = {
        series: [
          {
            type: "liquidFill", //水位图
            radius: "90%", //显示比例
            center: ["50%", "50%"], //中心点
            amplitude: 5, //水波振幅
            data: [0.8], // data个数代表波浪数
            color: [
              {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 1,
                    color: "#FA9F18",
                  },
                  {
                    offset: 0,
                    color: "#FA9F18",
                  },
                ],
                globalCoord: false,
              },
            ], //波浪颜色
            backgroundStyle: {
              borderWidth: 2, //外边框
              borderColor: "#FA9600", //边框颜色
              color: "#FEE0B4", //边框内部填充部分颜色
            },
            label: {
              //标签设置
              position: ["50%", "50%"],
              formatter: "优", //显示文本,
              textStyle: {
                fontSize: "22px", //文本字号,
                color: "#fff",
                fontFamily: "Source Han Sans-Regular",
                fontWeight: 500,
              },
            },
            outline: {
              // show: false
              borderDistance: 0,
              itemStyle: {
                borderWidth: 3,
                borderColor: "#FA9600",
              },
            },
          },
        ],
      };
      chartInstance.setOption(option);
      // 清理函数，防止内存泄漏等
      return () => {
        if (chartInstance != null && chartInstance.dispose) {
          chartInstance.dispose();
        }
      };
    }
  }, [sleepQualityRef.current !== null]);

  useEffect(() => {
    if (sleepEfficiencyRef.current) {
      const chartInstance = echarts.init(sleepEfficiencyRef.current);
      const option = {
        series: [
          {
            type: "liquidFill", //水位图
            radius: "90%", //显示比例
            center: ["50%", "50%"], //中心点
            amplitude: 5, //水波振幅
            data: [0.8], // data个数代表波浪数
            color: [
              {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 1,
                    color: "#FA9F18",
                  },
                  {
                    offset: 0,
                    color: "#FA9F18",
                  },
                ],
                globalCoord: false,
              },
            ], //波浪颜色
            backgroundStyle: {
              borderWidth: 2, //外边框
              borderColor: "#FA9600", //边框颜色
              color: "#FEE0B4", //边框内部填充部分颜色
            },
            label: {
              //标签设置
              position: ["50%", "50%"],
              formatter: "84%", //显示文本,
              textStyle: {
                fontSize: "22px", //文本字号,
                color: "#fff",
                fontFamily: "Source Han Sans-Regular",
                fontWeight: 500,
              },
            },
            outline: {
              // show: false
              borderDistance: 0,
              itemStyle: {
                borderWidth: 3,
                borderColor: "#FA9600",
              },
            },
          },
        ],
      };
      chartInstance.setOption(option);
      // 清理函数，防止内存泄漏等
      return () => {
        if (chartInstance != null && chartInstance.dispose) {
          chartInstance.dispose();
        }
      };
    }
  }, [sleepEfficiencyRef.current !== null]);

  return (
    <div>
      <h3
        className={css`
          border-left: 3px solid rgb(var(--primary-6));
          padding-left: 12px;
          margin-bottom: 16px;
        `}
      >
        睡眠报告
      </h3>
      {data.length > 0 ? (
        <div className="sleep-report-container">
          <div className="sleep-report-container-message">
            <div className="sleep-report-container-message-item">
              <i>房间:</i>8231
            </div>
            <div className="sleep-report-container-message-item">
              <i>住户:</i>冯女士
            </div>

            <div className="sleep-report-container-message-item">
              <i>报告日期:</i>2024-08-23
            </div>

            <div className="sleep-report-container-message-item">
              <i>生成时间:</i>2024-08-27 16:17:32
            </div>
          </div>
          <div className="sleep-report-container-title">
            数据概览 <img src={overview} />
          </div>
          <div className="sleep-report-container-data">
            <div className="container-item">
              <img src={bed} />
              <div className="text">
                <div className="label">卧床时间</div>
                <div className="time">16小时47分钟</div>
              </div>
            </div>
            <div className="container-item">
              <img src={sleepIcon} />
              <div className="text">
                <div className="label">睡眠时间</div>
                <div className="time">16小时47分钟</div>
              </div>
            </div>
            <div className="container-item">
              <img src={awake} />
              <div className="text">
                <div className="label">清醒时间</div>
                <div className="time">16小时47分钟</div>
              </div>
            </div>
          </div>

          <div className="sleep-report-container-echarts">
            <div
              className="item"
              ref={sleepQualityRef}
              style={{ width: "140px", height: "140px" }}
            ></div>
            <div className="item">
              <Progress
                type="circle"
                percent={92}
                color={"#FA9600"}
                trailColor="#FFE1B5"
                width={140}
                strokeWidth={13}
                formatText={() => "92分"}
                style={{ borderRadius: "50" }}
                className="custom-progress"
              />
            </div>
            <div className="item" ref={sleepEfficiencyRef}></div>
          </div>

          <div className="sleep-report-container-echarts-title">
            <div className="sleep-report-container-echarts-title-item">
              睡眠质量
            </div>
            <div className="sleep-report-container-echarts-title-item">
              睡眠评分
            </div>
            <div className="sleep-report-container-echarts-title-item">
              睡眠效率
            </div>
          </div>
          <div className="sleep-report-container-title">
            数据总结 <img src={overview} />
          </div>
          <div className="container">
            {data.map((v: any, i: number) => (
              <div key={i} className="container-item">
                <div
                  className="container-item-right"
                  style={{ background: v.rightBackground }}
                >
                  {reversedArray.map((num: any) => (
                    <div
                      key={num}
                      className="item"
                      style={{
                        borderColor: v.borderColor,
                        borderBottom: v.border == "none" ? "none" : "1px",
                      }}
                    ></div>
                  ))}
                  {v.time.map((el: any) => (
                    <div
                      key={el}
                      className="diffTime"
                      style={{
                        background: v.leftBackground,
                        left: el.left + "px",
                        width: el.width + "px",
                      }}
                    >
                      <Popover
                        trigger="hover"
                        content={
                          <span
                            className={css`
                              color: #796060;
                            `}
                          >
                            {el.title.map((title: any, titleIndex: number) => (
                              <p
                                className={css`
                                  font-size: 14px;
                                `}
                                key={titleIndex}
                              >
                                {title}
                              </p>
                            ))}
                          </span>
                        }
                      >
                        <div
                          className={css`
                            width: 100%;
                            height: 100%;
                          `}
                        ></div>
                      </Popover>
                    </div>
                  ))}
                </div>
              </div>
            ))}
            <div className="container-item-num">
              {reversedArray.map((num: any) => (
                <div
                  key={num}
                  style={{
                    textAlign: num < 10 ? "left" : "center",
                  }}
                >
                  {num < 10 ? `0${num}` : `${num}`}时
                </div>
              ))}
              <div style={{ textAlign: "center" }}>09时</div>
            </div>
          </div>
          <div className="container-total">
            {data.map((v: any, i: number) => (
              <div className="container-total-item" key={i}>
                <div className="container-total-item-text">
                  <div
                    className="span"
                    style={{ background: v.leftBackground }}
                  ></div>
                  {v.name}
                </div>
                <div className="container-total-item-time">{v.timeStr}</div>
              </div>
            ))}
          </div>
          <div className="sleep-report-container-atitle">
            <img src={sleep} />
            过去7天睡眠时间
          </div>

          <div className="sleep-report-container-data">
            <div className="container-li">
              <div className="container-item">
                <div className="img">
                  <img style={{ width: 20, height: 1 }} src={average} />
                </div>
                <div className="text">
                  <div className="label">平均睡眠时间</div>
                  <div className="time">6小时54分钟</div>
                </div>
              </div>
              <div className="container-item">
                <div className="img">
                  <img src={sleep} />
                </div>
                <div className="text">
                  <div className="label">最大睡眠时长</div>
                  <div className="time">8小时21分钟</div>
                </div>
              </div>
              <div className="container-item">
                <div className="img">
                  <img src={sleep} />
                </div>
                <div className="text">
                  <div className="label">最短睡眠时长</div>
                  <div className="time">16小时47分钟</div>
                </div>
              </div>
            </div>
          </div>
          <div className="sleep-report-container-history-ecahrts">
            <div
              ref={historyRef}
              className="sleep-report-container-history-ecahrts-item"
              style={{ background: "#ffefef" }}
            >
              {historyEcahrtsData.map((v: any) => (
                <div key={v.date} className="item"></div>
              ))}
            </div>

            <div
              className="sleep-report-container-history-ecahrts-item"
              style={{ background: "#fff4e4" }}
            >
              {historyEcahrtsData.map((v: any) => (
                <div key={v.date} className="item"></div>
              ))}
            </div>

            <div
              className="sleep-report-container-history-ecahrts-item"
              style={{
                background: "#f3f4ff",
                borderBottom: "1px solid #d8d8d8",
              }}
            >
              {historyEcahrtsData.map((v: any) => (
                <div key={v.date} className="item"></div>
              ))}
            </div>

            <div
              className="sleep-report-container-history-ecahrts-item"
              style={{ position: "absolute", top: 165, left: 0 }}
            >
              {historyEcahrtsData.map((v: any) => (
                <div key={v.date} className="item" style={{ border: "none" }}>
                  {v.date}
                </div>
              ))}
            </div>

            <div className="history-xios">
              <span>12</span> <span>8</span> <span>4</span> <span>0</span>
            </div>
            {historyEcahrtsData.map((v: any) => (
              <div
                key={v.date}
                className="history-color"
                style={{ left: v.left, height: v.height }}
              >
                <Popover
                  trigger="hover"
                  content={
                    <span
                      className={css`
                        color: #796060;
                      `}
                    >
                      {v.title}
                    </span>
                  }
                >
                  <div
                    className={css`
                      width: 100%;
                      height: 100%;
                    `}
                  ></div>
                </Popover>
              </div>
            ))}
            <div
              className="history-average"
              style={{ height: averageNum }}
            ></div>
          </div>
        </div>
      ) : (
        <div
          className={css`
            text-align: center;
            margin-top: 52px;
          `}
        >
          暂无数据
        </div>
      )}
    </div>
  );
};
